import Taro, { Component } from '@tarojs/taro';
import { Button, View, Form, Input, Label } from '@doctorwork/components';
import { connect } from '@tarojs/redux';
import Navigate from '../../components/Navigate/index';
import { rewriteAddMTA } from '../../model/utils/rewrite';
import './index.styl';

const appId = process.env.appId;

@connect(({ auth, loading }) => ({
    ...auth,
    isLoad: loading.effects['auth/getauthList'],
    isLoadMore: loading.effects['auths/loadMore']
}))
@rewriteAddMTA
export default class Index extends Component {
    config = {
        navigationBarTitleText: ''
    };
    constructor(props) {
        super(props);
        this.state = {
            canGetCode: true,
            timeRemain: 60
        };
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.canGetCode && nextProps.timeRemain) {
            if (this.timer) {
                clearInterval(this.timer);
            }
            let timeRemain = 60;
            let _this = this;
            _this.props.dispatch({
                type: 'auth/save',
                payload: {
                    canGetCode: false
                }
            });
            this.timer = setInterval(function() {
                if (timeRemain > 0) {
                    _this.setState({
                        canGetCode: false,
                        timeRemain
                    });
                    timeRemain--;
                } else {
                    _this.setState({
                        canGetCode: true
                    });
                    _this.props.dispatch({
                        type: 'auth/save',
                        payload: {
                            canGetCode: true,
                            timeRemain: 0
                        }
                    });
                    clearInterval(_this.timer);
                }
            }, 1000);
        }
    }
    componentWillMount() {
        console.log('进行鉴权');
        this.props.dispatch({
            type: 'analyse/set',
            payload: {
                name: 'login_start',
                data: {
                    place: this.$router.params
                }
            }
        });
        this.props.dispatch({
            type: 'auth/save',
            payload: {
                router: this.$router.params
            }
        });
        // TODO 这里以后不用可以删除
        //this.props.dispatch({ type: 'auth/loginMiniApp' });
    }
    componentWillUnmount() {
        this.props.dispatch({
            type: '$error/save',
            payload: {
                authTime: ''
            }
        });
    }

    //微信登录
    onGetPhoneNumber = async e => {
        //上报微信登录的点击次数
        wx.reportAnalytics('wechat_login', {
            number: 1
        });

        const { encryptedData, iv } = e.detail;
        if (encryptedData) {
            const params = {
                appId,
                encryptedData,
                iv
            };
            this.props.dispatch({
                type: 'auth/bindPhoneSmart',
                payload: params
            });
        }
    };
    // 电话号码输入
    onBindPhone = () => {
        //上报手机号登录次数
        // wx.reportAnalytics('phone_login', {
        //     number: 1,
        // });
        this.props.dispatch({
            type: 'analyse/set',
            payload: {
                name: 'phone_login',
                data: {
                    number: 1
                }
            }
        });
        this.props.dispatch({
            type: 'auth/save',
            payload: { showBindMode: true }
        });
    };
    // 关闭弹窗
    onCloseMode = () => {
        this.props.dispatch({
            type: 'auth/save',
            payload: { showBindMode: false }
        });
    };
    // 获取验证码
    onGetValicode = async () => {
        const pattern = /^((1[3,4,5,6,7,8,9]))\d{9}$/;
        const { phone } = this.props;
        if (!pattern.test(phone)) {
            this.props.dispatch({
                type: '$error/other',
                payload: { errmsg: '手机号不合法' }
            });
            return false;
        }

        if (this.state.disableGetCode) return;
        this.props.dispatch({
            type: 'save',
            payload: {
                disableGetCode: true
            }
        });
        this.props.dispatch({
            type: 'auth/getValidateCode',
            payload: {
                smsType: 1,
                phone: this.props.phone
            }
        });
    };
    onPhoneInput = e => {
        this.props.dispatch({
            type: 'auth/save',
            payload: { phone: e.detail.value }
        });
    };
    onCodeInput = e => {
        this.props.dispatch({
            type: 'auth/save',
            payload: { valiCode: e.detail.value }
        });
    };
    onRegister = async () => {
        const { phone, valiCode } = this.props;
        // 1. 校验手机号和验证码
        if (!phone) {
            this.props.dispatch({
                type: '$error/other',
                payload: { errmsg: '请输入手机号' }
            });
            return false;
        }
        if (!valiCode) {
            this.props.dispatch({
                type: '$error/other',
                payload: { errmsg: '请输入验证码' }
            });
            return false;
        }
        this.bindPhoneRequest();
    };

    // 带验证码绑定手机号
    bindPhoneRequest = async () => {
        const { phone, valiCode } = this.props;
        this.props.dispatch({
            type: 'auth/bindPhone',
            payload: { phone, verifyCode: valiCode }
        });
    };

    render() {
        const { showBindMode, phone, valiCode, disableGetCode } = this.props;
        const { timeRemain, canGetCode } = this.state;
        return (
            <View>
                <Navigate
                    title=' '
                    color='black'
                    backgroundColor='white'
                    backTextColor='black'
                />
                <View className='avatar'>
                    <image src={require('./imgs/default-avatar.png')} />
                    <View>
                        <Label>你好，请用手机号登录/注册～</Label>
                    </View>
                </View>
                <View className='bind-phone'>
                    <Button
                        open-type='getPhoneNumber'
                        onGetPhoneNumber={this.onGetPhoneNumber}
                    >
                        微信绑定手机号快速登录
                    </Button>
                    <View>
                        <Label onClick={this.onBindPhone.bind(this)} data-name='手动输入手机号登录'>
                            手动输入手机号登录
                        </Label>
                    </View>
                </View>
                {showBindMode ? (
                    <View className='alert-container'>
                        <View className='alert-content'>
                            <Form>
                                <Label className='title'>手机号登录/注册</Label>
                                <View>
                                    <Input
                                        type='text'
                                        placeholder='输入手机号'
                                        maxlength='11'
                                        value={phone}
                                        onInput={this.onPhoneInput.bind(this)}
                                    />
                                </View>
                                <View className='relative'>
                                    <Input
                                        type='text'
                                        placeholder='短信验证码'
                                        maxlength='4'
                                        value={valiCode}
                                        onInput={this.onCodeInput.bind(this)}
                                    />
                                    {canGetCode ? (
                                        <Label
                                            onClick={this.onGetValicode.bind(
                                                this
                                            )}
                                            disabled={disableGetCode}
                                            data-name='获取验证码'
                                        >
                                            获取验证码
                                        </Label>
                                    ) : (
                                        <Label>{timeRemain}秒后重新获取</Label>
                                    )}
                                </View>
                                <Button onClick={this.onRegister.bind(this)} data-name='登录/注册'>
                                    {' '}
                                    登录/注册{' '}
                                </Button>
                                <Label
                                    onClick={this.onCloseMode.bind(this)}
                                    className='close'
                                    data-name='关闭'
                                >
                                    关闭
                                </Label>
                            </Form>
                        </View>
                    </View>
                ) : (
                    ''
                )}
            </View>
        );
    }
}
